package com.hylanda.pb.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hylanda.pb.model.ReportModel;
import com.hylanda.pb.service.PowerBiService;

@Controller
public class PowerBiToolController {
	@Autowired
	private PowerBiService powerBiService;
	private static final String prefix = "pb/";
	//页面加载
	@RequestMapping(value={"/powerbitool/home"}, method = RequestMethod.GET)
	public String onload() {
		return prefix+"powerbitool/powerbi_import";
	}
	
	@RequestMapping(value={"/powerbitool/report/pbix"}, method = RequestMethod.POST)
	@ResponseBody
	public String importPbix(HttpServletRequest req, ReportModel model){	
		Part part=null;
		try {
			part=req.getPart("upload");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}
		if(part==null)  return "必须上传报表文件";
		String fileName = part.getHeader("content-disposition").split(";")[2].split("\"")[1];
		if(fileName.lastIndexOf(".pbix")<0)  return "报表格式不正确";
		return powerBiService.importPbix(model, fileName, part);
	}
	
	@RequestMapping(value = "/powerbitool/report/status", method = {RequestMethod.GET})
	@ResponseBody
	public String getImportStatus(ReportModel model, @RequestParam(value = "importId", required = true) String importID){
		if(StringUtils.isEmpty(importID)){
			return "必须输入导入id";
		}
		model.setImportID(importID);
		return powerBiService.getImportStatus(model);
	}
	
	@RequestMapping(value = {"/powerbitool/report/gatewayds"}, method = RequestMethod.GET)
	@ResponseBody
	public String getGateWayDs(ReportModel model, @RequestParam(value = "datasetID", required = true) String datasetID){
		if(StringUtils.isEmpty(datasetID)){
			return "必须输入数据集ID";
		}
		model.setDataSetID(datasetID);
		return powerBiService.getGateWayDs(model);
	}
	
	@RequestMapping(value = {"/powerbitool/report/datasource"}, method = RequestMethod.GET)
	@ResponseBody
	public String patchDatasource(ReportModel model, @RequestParam(value = "datasourceID", required = true) String datasourceID,
			@RequestParam(value = "gatewayID", required = true) String gateWayID){
		if(StringUtils.isEmpty(gateWayID)){
			return "必须输入网关ID";
		}
		if(StringUtils.isEmpty(datasourceID)){
			return "必须输入数据源ID";
		}
		model.setGateWayID(gateWayID);
		model.setDatasourceID(datasourceID);
		return powerBiService.patchDatasource(model);
	}
}
